/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.phamapply.client.widget.inpharmacyreturn;

import java.util.ArrayList;
import java.util.List;

import net.carefx.fc.framework.web.gwt.util.FcUtils;
import net.carefx.framework.container.client.context.AppContext;

import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.web.gwt.client.widget.FcMessageBox;
import com.th.supcom.pds.common.client.commom.PdsClientDateUtils;
import com.th.supcom.pds.common.enums.PhamReturnIndicatorConfig;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.phamapply.client.common.InpPhamApplyServiceFactory;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyDetailModel;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyPatInfoModel;
import com.th.supcom.pds.phamapply.client.model.PrescSearchDTOModel;
import com.th.supcom.pds.phamapply.client.service.NurseReturnRpcAsync;

/**
 * 门诊退药Action
 * 
 * @author yzhang
 */
/**
 *
 */
public class NurseReturnAction
{
    private NurseReturnMainPanel m_mainPanel;
    private NurseReturnFields m_nurseReturnFields;
    private NurseReturnGridPanel m_nurseReturnGridPanel;
    private NurseReturnButtons m_nurseReturnButtons;

    private final static NurseReturnRpcAsync S_NURSE_RETURN_RPC_ASYNC = InpPhamApplyServiceFactory.getNurseReturnService ();

    /**
     * 构造函数
     */
    public NurseReturnAction ()
    {

    }

    /**
     * 就诊次数下拉框 改变时 action
     */
    public void watchTimesChange ()
    {
        InpPhamApplyPatInfoModel selectedModel = m_nurseReturnFields.getWatchTimes ().getValue ();
        if (selectedModel == null)
        {
            return;
        }
        setPatInfoByBedNo (selectedModel);
        m_nurseReturnFields.getBeginField ().setValue (selectedModel.getNewInDeptDate ());
        m_nurseReturnFields.getEndField ()
                           .setValue (selectedModel.getDischargeDeptDate () == null ? FcUtils.getCurrentServerDateTimeForClient ()
                                                                                   : selectedModel.getDischargeDeptDate ());
    }

    /**
     * 通过床号查询患者信息
     * 
     * @param bedNo
     */
    public void getPatiInfoByBedNo (String bedNo)
    {
        if (null == bedNo)
        {
            return;
        }
        String nurseUnitCode = ClientUtils.getOrgModel().getOrgCode();
        mask ();
        S_NURSE_RETURN_RPC_ASYNC.getPatInfoByBedNo (bedNo, nurseUnitCode,
                                                    new AsyncCallback <InpPhamApplyPatInfoModel> ()
                                                    {

                                                        @Override
                                                        public void onFailure (Throwable caught)
                                                        {
                                                            clear (false);
                                                            ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                         m_nurseReturnFields.getBedNoField ());
                                                            unmask ();
                                                        }

                                                        @Override
                                                        public void onSuccess (InpPhamApplyPatInfoModel result)
                                                        {
                                                            setPatInfoByBedNo (result);
                                                            findInPatientInfoByPatientId (result.getPatientId ());
                                                            unmask ();
                                                        }
                                                    });
    }

    /**
     * 通过患者ID查询到患者信息后，展现到面板上
     * 
     * @param result
     */
    private void setPatInfoByBedNo (InpPhamApplyPatInfoModel result)
    {
        m_nurseReturnFields.getPatiIdField ().setValue (result.getPatientId ());
        m_nurseReturnFields.getPatiNameField ().setValue (result.getPatName ());
        m_nurseReturnFields.getPatiIdForDisplayField ().setValue (result.getPatientId ());
        m_nurseReturnFields.getSexField ().setValue (result.getGenderName ());
        m_nurseReturnFields.getBedNoForDisplayField ().setValue (result.getBedNo ());
        m_nurseReturnFields.getPrepaidField ().setValue (result.getAvailablePrepayment ());
        m_nurseReturnFields.getChargeTypeName ().setValue (result.getChargeTypeName ());
        m_nurseReturnFields.getWatchTimesForDisplay ().setValue (result.getVisitId ().toString ());
        m_nurseReturnFields.getDeptAdmissionNameField ().setValue (result.getNewInDeptName ());
        m_nurseReturnFields.getDeptAdmissionDateField ()
                           .setValue (PdsClientDateUtils.getYMDHmsFormat (result.getNewInDeptDate ()));
        int noEndDay = PdsClientDateUtils.getIntervalDay (result.getNewInDeptDate (),
                                                          FcUtils.getCurrentServerDateTimeForClient ());
        int endDays = PdsClientDateUtils.getIntervalDay (result.getNewInDeptDate (), result.getDischargeDeptDate ());
        m_nurseReturnFields.getDeptAdmissionDays ().setValue (result.getDischargeDeptDate () == null ? noEndDay
                                                                                                    : endDays);
    }

    /**
     * 获取患者PID获取所有的住院记录列表. 按照次数倒叙排列.
     */
    public void findInPatientInfoByPatientId (String patientId)
    {
        if (patientId == null)
        {
            return;
        }
        mask ();
        S_NURSE_RETURN_RPC_ASYNC.findPatInfoByPatientId (patientId,
                                                         new AsyncCallback <List <InpPhamApplyPatInfoModel>> ()
                                                         {
                                                             @Override
                                                             public void onSuccess (List <InpPhamApplyPatInfoModel> result)
                                                             {
                                                                 m_nurseReturnFields.getPatiInfoListStore ()
                                                                                    .removeAll ();
                                                                 m_nurseReturnFields.getPatiInfoListStore ()
                                                                                    .add (result);
                                                                 m_nurseReturnFields.getWatchTimes ()
                                                                                    .setValue (result.get (0));
                                                                 setPatInfoByBedNo (result.get (0));
                                                                 unmask ();
                                                                 m_nurseReturnGridPanel.getStore ().removeAll ();
                                                                 m_nurseReturnButtons.getQueryBtn ().focus ();
                                                             }

                                                             @Override
                                                             public void onFailure (Throwable caught)
                                                             {
                                                                 clear (false);
                                                                 ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                              m_nurseReturnFields.getPatiIdField ());
                                                                 unmask ();
                                                             }
                                                         });
    }

    /**
     * 查询患者费用明细
     */
    public void findChargeItemByExample ()
    {
        PrescSearchDTOModel prescSearchDTOModel = new PrescSearchDTOModel ();
        if (m_nurseReturnFields.getWatchTimes ().getValue () == null)
        {
            return;
        }
        prescSearchDTOModel.setPatientId (m_nurseReturnFields.getPatiIdForDisplayField ().getValue ());
        prescSearchDTOModel.setVisitId (m_nurseReturnFields.getWatchTimes ().getValue ().getVisitId ());
        prescSearchDTOModel.setNurseUnit (ClientUtils.getOrgModel().getOrgCode());
        mask ();
        S_NURSE_RETURN_RPC_ASYNC.findChargeItemByExample (prescSearchDTOModel,
                                                          new AsyncCallback <List <InpPhamApplyDetailModel>> ()
                                                          {

                                                              @Override
                                                              public void onSuccess (List <InpPhamApplyDetailModel> result)
                                                              {
                                                                  m_nurseReturnGridPanel.getStore ().removeAll ();
                                                                  m_nurseReturnGridPanel.getStore ().add (result);
                                                                  unmask ();
                                                              }

                                                              @Override
                                                              public void onFailure (Throwable caught)
                                                              {
                                                                  m_nurseReturnGridPanel.getStore ().removeAll ();
                                                                  ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                               m_nurseReturnFields.getBedNoField ());
                                                                  unmask ();
                                                              }
                                                          });
    }

    /**
     * 生成电子退药单/退药处方action
     * 
     * @param successComponent
     * @param failComponent
     */
    public void confirm (final Component successComponent, final Component failComponent)
    {
        if (m_nurseReturnGridPanel.getModels ().isEmpty ())
        {
            ClientUtils.alertMessageBox ("请先查询到相关信息再进行此操作！", failComponent);
            return;
        }
        final List <InpPhamApplyDetailModel> applyDetailModels = getReturnInfo ();
        if (applyDetailModels.isEmpty ())
        {
            ClientUtils.alertMessageBox ("请先填写相关信息再进行此操作！", failComponent);
            return;
        }
        Boolean returnFlag = false;
        Boolean returnConfig = true;
        for (InpPhamApplyDetailModel inpPhamApplyDetailModel : applyDetailModels)
        {
            if (inpPhamApplyDetailModel.getPhamReturnIndicator () != null)
            {
                returnFlag = true;
            }
            if (inpPhamApplyDetailModel.getPhamReturnIndicator () != null
                && PhamReturnIndicatorConfig.NoReturn.getEnumCode ()
                                                     .equals (inpPhamApplyDetailModel.getPhamReturnIndicatorConfig ()))
            {
                returnConfig = false;
            }
        }
        final Boolean returnConfigComfirm = returnConfig;
        if (returnFlag)
        {
            FcMessageBox.confirm ("提示", "所退药品中有不可退药品,确定要生成电子退药单吗?", new Listener <MessageBoxEvent> ()
            {
                @Override
                public void handleEvent (MessageBoxEvent be)
                {
                    if (be.getButtonClicked ().getText ().equals ("否"))
                    {
                        return;
                    }
                    if (!returnConfigComfirm)
                    {
                        ClientUtils.alertMessageBox ("所退药品为不可退药品，不能进行退药操作！", null);
                        return;
                    }
                    doGenerate (applyDetailModels, successComponent, failComponent);
                }
            }, Dialog.YES);
        }
        else
        {
            FcMessageBox.confirm ("提示", "确定要生成电子退药单吗?", new Listener <MessageBoxEvent> ()
            {
                @Override
                public void handleEvent (MessageBoxEvent be)
                {
                    if (be.getButtonClicked ().getText ().equals ("否"))
                    {
                        return;
                    }
                    doGenerate (applyDetailModels, successComponent, failComponent);
                }
            }, Dialog.YES);
        }
    }

    /**
     * 返回 退药数据
     * 
     * @return
     */
    private List <InpPhamApplyDetailModel> getReturnInfo ()
    {
        List <InpPhamApplyDetailModel> allInfo = m_nurseReturnGridPanel.getGrid ().getStore ().getModels ();
        List <InpPhamApplyDetailModel> needInfo = new ArrayList <InpPhamApplyDetailModel> ();
        for (InpPhamApplyDetailModel info : allInfo)
        {
            if (info.getWithdrawAmount () != null && info.getWithdrawAmount () != 0)
            {
                needInfo.add (info);
            }
        }
        return needInfo;
    }

    /**
     * 生成电子退药单操作
     * 
     * @param successComponent
     * @param failComponent
     * @param be
     */
    private void doGenerate (List <InpPhamApplyDetailModel> applyDetailModels, final Component successComponent,
                             final Component failComponent)
    {

        String operator = ClientUtils.geteEmpModel ().getEmpCode ();
        String nurseUnit =ClientUtils.getOrgModel().getOrgCode();
        InpPhamApplyPatInfoModel inpPhamApplyPatInfoModel = m_nurseReturnFields.getWatchTimes ().getValue ();
        S_NURSE_RETURN_RPC_ASYNC.generateBill (applyDetailModels, nurseUnit, operator, inpPhamApplyPatInfoModel,
                                               new AsyncCallback <Void> ()
                                               {

                                                   @Override
                                                   public void onFailure (Throwable caught)
                                                   {

                                                       ClientUtils.alertMessageBox (caught.getMessage (), failComponent);
                                                       clear (true);
                                                       unmask ();

                                                   }

                                                   @Override
                                                   public void onSuccess (Void result)
                                                   {

                                                       Info.display ("提示", "成功生成电子退药单!");
                                                       clear (true);

                                                       successComponent.focus ();
                                                       unmask ();
                                                   }
                                               });
    }

    /**
     * 清除
     * 
     * @param isClearAll true : clear all false : no clear input
     */
    public void clear (boolean isClearAll)
    {
        if (isClearAll)
        {
            m_nurseReturnFields.getBedNoField ().setValue (null);
            m_nurseReturnFields.getPatiIdField ().setValue (null);
        }
        m_nurseReturnGridPanel.getStore ().removeAll ();
        m_nurseReturnButtons.getReturnBill ().setValue (true);
        m_nurseReturnButtons.getReturnWithoutDrug ().setValue (true);
        m_nurseReturnFields.removeAll ();
    }

    private void mask ()
    {
        m_mainPanel.mask ("加载中...");
    }

    private void unmask ()
    {
        m_mainPanel.unmask ();
    }

    public void setNurseReturnFields (NurseReturnFields nurseReturnFields)
    {
        m_nurseReturnFields = nurseReturnFields;
    }

    public void setNurseReturnGridPanel (NurseReturnGridPanel nurseReturnGridPanel)
    {
        m_nurseReturnGridPanel = nurseReturnGridPanel;
    }

    public void setNurseReturnButtons (NurseReturnButtons nurseReturnButtons)
    {
        m_nurseReturnButtons = nurseReturnButtons;
    }

    public void setMainPanel (NurseReturnMainPanel mainPanel)
    {
        m_mainPanel = mainPanel;
    }

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
}
